package com.lightkits.wms.domain.purchasereceive.service.impl;

import com.lightkits.common.db.entity.ScmPoHeader;
import com.lightkits.common.db.entity.ScmPoLine;
import com.lightkits.common.db.entity.ScmPoTrack;
import com.lightkits.common.db.entity.event.BdEventRecord;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;

import com.lightkits.wms.domain.purchasereceive.service.CreateParamsDomain;
import com.lightkits.wms.domain.purchasereceive.service.CreatePoParamsDomain;
import com.lightkits.wms.domain.stocktransfer.service.impl.SubStockTransferDomainImpl;
import com.lightkits.wms.dto.deliveryticket.models.TicketHeadDTO;
import com.lightkits.wms.dto.deliveryticket.models.TicketLineDTO;
import com.lightkits.wms.dto.purchasereceive.models.SavePoParamsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * CreatePoParamsDomainImpl
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/26 15:14
 */
@Service
public class CreatePoParamsDomainImpl implements CreatePoParamsDomain {
    private final CreateParamsDomain createParamsDomain;
    private static final Logger LOGGER = LoggerFactory.getLogger(SubStockTransferDomainImpl.class);

    @Autowired
    public CreatePoParamsDomainImpl(CreateParamsDomain createParamsDomain) {
        this.createParamsDomain = createParamsDomain;
    }


    @Override
    public CheckResult<ScmPoHeader> createHead(String poId) {
        CheckResult<ScmPoHeader> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        try {
            ScmPoHeader header = new ScmPoHeader().selectById(poId);
            header.setPoStatus("COMPLETED");
            header.setLastStatus("COMPLETED");
            //create Records
            List<BdEventRecord> records = new ArrayList<>();
            BdEventRecord record = createParamsDomain.createRecord("PO", header.getId(),
                    "PO_STATUS", "COMPLETED");
            records.add(record);
            header.store(records);
            checkResult.setData(header);
        } catch (Exception e) {
            LOGGER.error("Create Scm PO Header error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    @Override
    public CheckResult<ScmPoLine> createLines(SavePoParamsDTO dto) {
        CheckResult<ScmPoLine> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        try {
            ScmPoLine line = new ScmPoLine().selectById(dto.getPoLineId());

            //create Records
            List<BdEventRecord> records = new ArrayList<>();

            if (!ObjectUtil.isNullOrEmpty(dto.getReceiveQty())) {
                line.setRecievedQty(ObjectUtil.isEmpty(line.getRecievedQty()) ?
                        new BigDecimal(0) : line.getRecievedQty());
                line.setRecievedQty(line.getRecievedQty().add(new BigDecimal(dto.getReceiveQty())));
                BdEventRecord receiveRecord = createParamsDomain.createRecord("PO_LINE",
                        ParseUtil.tryLongWithException(dto.getPoLineId())
                        , dto.getReceiveQty(), "RECEIVED_QTY");
                records.add(receiveRecord);
                List<ScmPoTrack> poTracks=new ArrayList<>();
                String actionRecords="订单已发货数量" + dto.getReceiveQty();
                ScmPoTrack poTrack=createParamsDomain.createPoTrack(dto,actionRecords);
                poTracks.add(poTrack);
                line.store("PO_TRACK",poTracks);
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getReturnQty())) {
                line.setReturnedQty(ObjectUtil.isEmpty(line.getReturnedQty()) ?
                        new BigDecimal(0) : line.getReturnedQty());
                line.setReturnedQty(line.getReturnedQty().add(new BigDecimal(dto.getReturnQty())));
                BdEventRecord returnRecords = createParamsDomain.createRecord("PO_LINE",
                        ParseUtil.tryLongWithException(dto.getPoLineId()),
                        dto.getReturnQty(), "RETURNED_QTY");
                records.add(returnRecords);
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getQcNgQty())) {
                line.setQcNgQty(ObjectUtil.isEmpty(line.getQcNgQty()) ?
                        new BigDecimal(0) : line.getQcNgQty());
                line.setQcNgQty(line.getQcNgQty().add(new BigDecimal(dto.getQcNgQty())));
                BdEventRecord qcNgRecords = createParamsDomain.createRecord("PO_LINE",
                        ParseUtil.tryLongWithException(dto.getPoLineId()),
                        dto.getQcNgQty(), "QC_NG_QTY");
                records.add(qcNgRecords);
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getInventoryQty())) {
                line.setInventoryQty(ObjectUtil.isEmpty(line.getInventoryQty()) ?
                        new BigDecimal(0) : line.getInventoryQty());
                line.setInventoryQty(line.getInventoryQty().add(new BigDecimal(dto.getInventoryQty())));
                BdEventRecord inventoryRecords = createParamsDomain.createRecord("PO_LINE",
                        ParseUtil.tryLongWithException(dto.getPoLineId()),
                        dto.getInventoryQty(), "INVENTORY_QTY");
                records.add(inventoryRecords);
            }
            if(!ObjectUtil.isNullOrEmpty(dto.getReceiveWarehouseId())){
                line.setRecieveWarehouseId(ParseUtil.tryLongWithException(dto.getReceiveWarehouseId()));
            }
            if(!ObjectUtil.isNullOrEmpty(dto.getReceiveWmAreaId())){
                line.setRecieveWmAreaId(ParseUtil.tryLongWithException(dto.getReceiveWmAreaId()));
            }
            if(!ObjectUtil.isNullOrEmpty(dto.getInventoryWarehouseId())){
                line.setInventoryWarehouseId(ParseUtil.tryLongWithException(dto.getInventoryWarehouseId()));
            }
            if(!ObjectUtil.isNullOrEmpty(dto.getInventoryWmAreaId())){
                line.setInventoryWmAreaId(ParseUtil.tryLongWithException(dto.getInventoryWmAreaId()));
            }

            line.store("RECORDS",records);
            checkResult.setData(line);

        } catch (Exception e) {
            LOGGER.error("Create Scm PO Lines error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    @Override
    public CheckResult<TicketHeadDTO> createTicketHead(SavePoParamsDTO dto){
        CheckResult<TicketHeadDTO> checkResult=new CheckResult<>();
        checkResult.setSuccessful(true);
        try{
            TicketHeadDTO headDTO=new TicketHeadDTO();
            headDTO.setOrgId(dto.getOrgId());
            headDTO.setReceiveWorkerId(dto.getReceiveWorker());
            ScmPoHeader header=new ScmPoHeader().selectById(dto.getPoId());
            headDTO.setPartyId(header.getSupplierId().toString());
            if(!ObjectUtil.isEmpty(header.getSupplierSiteId())){
                headDTO.setPartySiteId(header.getSupplierSiteId().toString());
            }
            headDTO.setPoLineId(dto.getPoLineId());
            headDTO.setEventRequestId(dto.getEventRequestId());
            headDTO.setRemark(dto.getRemark());
            headDTO.setTicketType("SELF");
            checkResult.setData(headDTO);
        } catch (Exception e) {
            LOGGER.error("Create Delivery Ticket Head error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    @Override
    public  CheckResult<TicketLineDTO> createTicketLine(SavePoParamsDTO dto){
        CheckResult<TicketLineDTO> checkResult=new CheckResult<>();
        checkResult.setSuccessful(true);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            TicketLineDTO lineDTO=new TicketLineDTO();
            lineDTO.setItemId(dto.getItemId());
            lineDTO.setUomCode(dto.getUomCode());
            lineDTO.setLot(dto.getLotCode());
            lineDTO.setReceiveQty(dto.getReceiveQty());
            lineDTO.setReturnQty(dto.getReturnQty());
            lineDTO.setInventoryQty(dto.getInventoryQty());
            lineDTO.setQcNgQty(dto.getQcNgQty());
            lineDTO.setPoId(dto.getPoId());
            lineDTO.setPoLineId(dto.getPoLineId());
            lineDTO.setOrgId(dto.getOrgId());
            lineDTO.setEventRequestId(dto.getEventRequestId());
            lineDTO.setReceiveWorkerId(dto.getReceiveWorker());
            lineDTO.setReceiveWarehouseId(dto.getReceiveWarehouseId());
            lineDTO.setReceiveWmArea(dto.getReceiveWmAreaId());
            lineDTO.setInventoryWarehouseId(dto.getInventoryWarehouseId());
            lineDTO.setInventoryWmAreaId(dto.getInventoryWmAreaId());
            lineDTO.setActualArraivalTime(format.format(new Date()));
            lineDTO.setPictureIds(dto.getPictureIds());
            lineDTO.setMoveTypeCode(dto.getMoveTypeCode());
            checkResult.setData(lineDTO);
        }catch (Exception e) {
            LOGGER.error("Create Delivery Ticket Line error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

}
